import re
import sys
import cgi
import settings
from google.appengine.api import users
from django.shortcuts import *
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.template.loader import render_to_string
from django.template import TemplateDoesNotExist


class HttpContext():
	def __init__(self, request):
		self.request = request
		self.current_user = users.get_current_user()
		self.base_url = request.META['wsgi.url_scheme'] + '://' + request.META['HTTP_HOST']
		self.url = request.get_full_path()
		self.full_url = '%s/%s' % (self.base_url, self.url)
		self.login_url = users.create_login_url(self.url)
		self.logout_url = users.create_logout_url(self.	url)
		self.is_mobile = self.detect_mobile()
	
	def render(self, template, format=None, extra_tokens=None):
		output = ''
		mimetype='text/html'
		if not format:
			format = 'html'
			if self.is_mobile:
				format = 'mobile'
			qformat = self.param('format')
			if qformat:
				format = qformat
				
		mimetype='text/html'
		if format in ('xml', 'atom', 'rss'):
			mimetype = 'text/xml'

		try:
			output = self.render_to_string(template, extra_tokens)
			if format == 'js':
				output = self.format_js(output)
		except TemplateDoesNotExist:
			raise Http404

		return HttpResponse(output, mimetype=mimetype)
	
	def render_to_string(self, template, extra_tokens=None):
		tokens = self.tokens();
		if extra_tokens:
			tokens.update(extra_tokens)
		return render_to_string(template, tokens)
	
	
	def tokens(self):
		return {
			'context': self,
			'request': self.request,
			'user': self.current_user,
			
			'url': self.url,
			'full_url': self.full_url,
			'login_url': self.login_url,
			'logout_url': self.logout_url,
			'continue_url': self.continue_url(),
			
			'params': self.request.REQUEST,
			'cookies': self.request.COOKIES,
			'meta': self.request.META,
			
			'version': '%s.%s' % (settings.APP['major_version'], self.request.META['CURRENT_VERSION_ID']),
			'app': settings.APP,
			
			'base_url': self.base_url,
			
			'http' : {
				'get': self.request.GET,
				'post': self.request.POST,
				'params': self.request.REQUEST,
				'cookies': self.request.COOKIES,
				'meta': self.request.META,
				'is_secure': self.request.is_secure(),
				'is_ajax': self.request.is_ajax(),
				'is_mobile': self.is_mobile
			}
		}

	def is_authenticated(self):
		return (self.current_user != None)
	
	def is_admin(self):
		return users.is_current_user_admin()

	def authenticate(self):
		return self.redirect(self.login_url)

	def redirect(self, url):
		return HttpResponseRedirect(url)
		#print 'Status: 302 Moved Temporarily'
		#print 'Location1:', url
		#print 'Pragma: no-cache'
		#print 'Content-Type: text/html'
		#hurl = cgi.escape(url, 1)
		#print '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML//EN">'
		#print '<html><head><title>Redirect (302)</title></head>'
		#print '<body><h1>302 Moved Temporarily</h1>'
		#print '<p>The answer to your request is located at'
		#print '<a href="%s">%s</a>.</body></html>' % (hurl, hurl)

	def redirect_continue(self):
		return self.redirect(self.continue_url())

	def param(self, name, default=None):
		if self.request.POST.has_key(name):
			return self.request.POST[name]
		if self.request.GET.has_key(name):
			return self.request.GET[name]
		return default
	
	def escape_name(self, name):
		return re.sub(r'[^\w]', '-', name.strip())
	
	def continue_url(self):
		continue_url = self.param('continue')
		if not continue_url:
			#if self.request.META.has_key('HTTP_REFERER'):
			#	continue_url = self.request.META['HTTP_REFERER']
			#else:
			#	continue_url = '/'
			continue_url = '/'
		return cgi.escape(continue_url)


	def detect_mobile(self):
		if 'is_mobile' in self.request.COOKIES:
			return str(self.request.COOKIES['is_mobile']) == '1'
		if "HTTP_X_OPERAMINI_FEATURES" in self.request.META:
			return True
		if "HTTP_ACCEPT" in self.request.META:
			accept = self.request.META["HTTP_ACCEPT"].lower()
			if 'application/vnd.wap.xhtml+xml' in accept:
				return True
		if "HTTP_USER_AGENT" in self.request.META:
			agent = self.request.META["HTTP_USER_AGENT"].lower()
			for keyword in settings.MOBILE_KEYWORDS:
				if keyword in agent:
					return True
		return False

	def format_js(self, input):
		lines = input.split('\n')
		output = ''
		for line in lines:
			if line and line != '':
				jline = line.replace(r'"', r'\"').replace('\n', '').replace('\r', '')
				output = output + '\ndocument.write("%s");' % jline
		return output
